package com.ybg.engine.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.ybg.util.LogUtil;
 /**
  * 统计老师上课的课表
 * @author huang nc
 * @since  2017年3月28日
 */
public class TeacherCourseTask extends Task {

    private static boolean running = false;
    public Map<String,Map<String,Object>> exitUserMap = new HashMap<String,Map<String,Object>>();
    public List<Map<String,Object>> updateUserList = new ArrayList<Map<String,Object>>();
    public List<Map<String,Object>> newUserList = new ArrayList<Map<String,Object>>();
    
	@Override
	public void run() throws Exception {
	 if (!enter()){
            throw new RuntimeException("调度已经在进行中");
        }
        LogUtil.warn("teacher-course-stati...begin........");
        long begin = new Date().getTime();

        System.out.println("你看到我了吗？老师上课课表");
        deleteHistory();
        insertTeacherCourseData();
        //TaskUtil.markProcess(jdbcTemplate, TaskName.UPDATE_STATUS, DateTimeUtil.getToday(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
        long end = new Date().getTime();
        LogUtil.info("本次任务用时 :" + (end - begin) / 1000 + "秒");
        LogUtil.warn("teacher-course-stati...begin........");
        leaving();
	}


	//清除之前课表的数据
	private void deleteHistory() {
        String sql = "delete from YBG_B_SCHEDULE_TEACHER ";
        int result = jdbcTemplate.update(sql);
        LogUtil.info("清除历史数据："+result+" 条");
	}

	//重新导入课表数据
	private void insertTeacherCourseData() {
		int insertSize = 0;
		String selectSql = "select count(xlh) as count, kcmc,kcdm,qsjsz,djj,skdd,xn,xq,skls,xqj,gh,dsz from ybg_b_schedule_xs group by kcdm,kcmc,qsjsz,djj,skdd,xn,xq,skls,xqj,gh,dsz";
		String insertSql = "insert into YBG_B_SCHEDULE_TEACHER (xlh,count,kcmc,kcdm,qsjsz,djj,skdd,xn,xq,skls,xqj,gh,dsz) values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(selectSql);
		if (list!= null &&list.size()!=0) {
			for (Map<String, Object> map : list) {
				insertSize = jdbcTemplate.update(insertSql,UUID.randomUUID().toString(),map.get("count")+"",map.get("kcmc")+"",map.get("kcdm")+"",map.get("qsjsz")+"",map.get("djj")+"",map.get("skdd")+"",map.get("xn")+"",map.get("xq")+"",map.get("skls")+"",map.get("xqj")+"",map.get("gh")+"",map.get("dsz")+"");
				insertSize += insertSize;
			}
		}
	}

	private synchronized boolean enter(){
        if(running){
            return false;
        }else{
            running = true;
            return true;
        }
    }

    private synchronized void leaving(){
        running = false;
    }

	@Override
	public String setSuccessResultMsg() {
		
		return "教师上课课表调度成功";
	}

}
